package com.qipay.excel.service;

import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/**
 * Creator: Yao
 * Date:    2017/12/3
 * For:
 * Other:
 */
@Component
public class ExcelUtils {

    // test.local
    private void download(HSSFWorkbook book) throws IOException {

        String filePath = String.format("D:\\data\\export\\%s.xls", UUID.randomUUID().toString());
        File file = new File(filePath);
        file.createNewFile();

        OutputStream outputStream = new FileOutputStream(file);
        book.write(outputStream);
        outputStream.flush();
        IOUtils.closeQuietly(outputStream);

        System.out.println(filePath);
    }


    // download
    public void download(HttpServletResponse resp, HSSFWorkbook book) {

        // check
        Assert.notNull(resp, "未提供响应对象");
        Assert.notNull(book, "未提供 Excel 文件");

        // init
        OutputStream respOutputStream = null;

        // write
        try {
            respOutputStream = resp.getOutputStream();
            book.write(respOutputStream);
            respOutputStream.flush();

//            download(book);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                IOUtils.closeQuietly(respOutputStream);
                book.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
